package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.doc.CourseDoc;
import cn.itsource.ymcc.dto.CourserSearchDto;
import cn.itsource.ymcc.heightmapper.HighlightResultMapper;
import cn.itsource.ymcc.repository.CourseElasticsearchRepository;
import cn.itsource.ymcc.result.PageList;
import cn.itsource.ymcc.service.ISearchService;
import cn.itsource.ymcc.vo.AggrsBucket;
import cn.itsource.ymcc.vo.EsAggsPageList;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements ISearchService {
    @Autowired
    private CourseElasticsearchRepository courseElasticsearchRepository;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;//返回高亮样式就用这个Api
    @Autowired
    private HighlightResultMapper highlightResultMapper;

    @Override
    public void saveCourse(CourseDoc doc) {
        courseElasticsearchRepository.save(doc);
    }

    @Override
    public PageList<CourseDoc> search(CourserSearchDto dto) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        //封装排序条件========================
        if(StringUtils.hasLength(dto.getSortField())){
            // dto.getSortField()  xl rq  xp pl
            String sortField = null;
            switch (dto.getSortField().toLowerCase()){
                case "xl": sortField="saleCount";break;
                case "xp": sortField="onlineTime";break;
                case "pl": sortField="commentCount";break;
                case "jg": sortField="price";break;
                case "rq": sortField="viewCount";break;
                default: break;
            }
            if(sortField != null){
                if(StringUtils.hasLength(dto.getSortType())){
                    SortOrder sortOrder = dto.getSortType().equalsIgnoreCase("ASC") ? SortOrder.ASC : SortOrder.DESC;
                    builder.withSort(new FieldSortBuilder(sortField).order(sortOrder));
                }
            }
        }
        //封装分页相关的参数===================  0 代表第一页
        builder.withPageable(PageRequest.of(dto.getPage()-1, dto.getRows()));
        //PageRequest pageRequest = PageRequest.of(dto.getPage()-1, dto.getRows());
        //封装查询条件========================
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //DSL查询  private String keyword;//关键字-------
        if(StringUtils.hasLength(dto.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("name",dto.getKeyword()));
        }
        //DSL过滤-----------------
        if(dto.getCourseTypeId() != null){
            boolQuery.filter(QueryBuilders.termQuery("courseTypeId",dto.getCourseTypeId()));
        }
        if(StringUtils.hasLength(dto.getGradeName())){
            boolQuery.filter(QueryBuilders.termQuery("gradeName",dto.getGradeName()));
        }
        if(StringUtils.hasLength(dto.getChargeName())){
            boolQuery.filter(QueryBuilders.termQuery("chargeName",dto.getChargeName()));
        }
        if(dto.getPriceMin() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin()));
        }
        if(dto.getPriceMax() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }
        /**
         * 设置高亮 三大步：
         *          1.设置高亮样式
         *          2.处理映射结果 准备映射器拷贝mapper使用
         *          3.使用映射器处理结果
         */
        builder.withHighlightFields(
                new HighlightBuilder.Field("name")
                        .preTags("<font style='color:blue'>")
                        .postTags("</font>"));
        // 添加聚合查询
        //添加等级名字聚合
        builder.addAggregation(AggregationBuilders.terms("aggsGradeName").field("gradeName"));
        //添加收费规则聚合
        builder.addAggregation(AggregationBuilders.terms("aggsChargeName").field("chargeName"));
        builder.withQuery(boolQuery);
        //搜索Es  ==========================
        NativeSearchQuery build = builder.build();
        //Page<CourseDoc> page = courseElasticsearchRepository.search(build);//  最重要
        // 要设置高亮 就要用这个
        AggregatedPage<CourseDoc> page = elasticsearchRestTemplate.queryForPage(build, CourseDoc.class, highlightResultMapper);
        //这里去那到设置了聚合的值，是一个map
        Map<String, Aggregation> maps = page.getAggregations().asMap();
        //那到里面的值 这两个是map里面Key 他们下面还有一堆东西
        ParsedStringTerms aggsGradeName = (ParsedStringTerms)maps.get("aggsGradeName");
        ParsedStringTerms aggsChargeName = (ParsedStringTerms)maps.get("aggsChargeName");
        // 处理等级的聚合
        List<AggrsBucket> aggrsBuckets = new ArrayList<>();
        aggsGradeName.getBuckets().forEach(bucket -> {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            AggrsBucket aggrsBucket = new AggrsBucket(key, docCount);
            aggrsBuckets.add(aggrsBucket);
        });
        //处理收费规则聚合
        List<AggrsBucket> aggrsBucketss = new ArrayList<>();
        aggsChargeName.getBuckets().forEach(bucket -> {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            AggrsBucket aggrsBucket = new AggrsBucket(key, docCount);
            aggrsBucketss.add(aggrsBucket);
        });
        //装进map中返回给前端
        Map<String,List<AggrsBucket>> map = new HashMap<>();
        //aggsGradeName
        map.put("aggsGradeName",aggrsBuckets);
        map.put("aggsChargeName",aggrsBucketss);

        //封装PageList返回 ==================
        return new EsAggsPageList<>(page.getTotalElements(),page.getContent(),map);
    }

    @Override
    public void deleteCourse(Long courseId) {
        courseElasticsearchRepository.deleteById(courseId);
    }

}
